<?php
	$BASE_DIR = '/usr/share/uggla/';

	require($BASE_DIR."inc/functions.php");
	require($BASE_DIR."inc/authorize.php");
	$stat = authorize();
	if($stat != 0) {
		header("Location: index.php?l=$stat"); /* gick inte */
		exit ();
	}
	
	  //Browser ska inte cache
	header("Cache-Control: no-cache, must-revalidate");
	header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");

    // Har användaren tryckt på Avbryt och därmed vill till huvudmenyn / föräldramenyn?
	if( isset($_POST['b_cancel']) OR isset($_POST['b_close']) ) {
		if( isset($_POST['parent_page']) )
			if( isset($_POST['parent_tab']) )
				header("Location: main.php?s=".$_POST['parent_page']."&t=".$_POST['parent_tab']);
			else
				header("Location: main.php?s=".$_POST['parent_page']);
		else
			header("Location: main.php");
		exit();
	}
    // Har användaren tryckt på Logga ut?
	if( isset($_POST['b_logout']) ) {
		header("Location: logout.php");
		exit();
	}


	$dir = "service/";
	$SERVICES_DIR = $BASE_DIR.'services/';
	$SERVICE = FALSE;
	$page = $BASE_DIR."inc/starter.php";

    // LDAP
        $dc=trim(file_get_contents("/etc/ldapbase"));
	$pw=trim(file_get_contents("/etc/ldap.secret"));


    // Ska information sparas?
	if( $_SERVER['REQUEST_METHOD'] == 'POST' || isset($_GET['do']) ) {
		$PAGESAVE = TRUE;
                if( isset($_GET['do']) )
                    unset( $_GET['do'] );
	} else {
		$PAGESAVE = FALSE;
	}

	if( isset($_GET['s']) && $_GET['s'] == 'log' ) {
		$page = $BASE_DIR."inc/log.php";
		$safe_s= "-";
	}
	else {
		$safe_s = "";
                $unsafe_s = "";
                if( isset($_GET['s']) ) $unsafe_s = $_GET["s"];
	    // Check, $_GET["s"]
		$dirarr = scandir($SERVICES_DIR);
		$hit = array_search($unsafe_s, $dirarr);
		if ( $hit !== false ) {
			$hit = $dirarr[$hit];
			if ( $hit != '.' && $hit != '..' ) {
				if ( is_dir($SERVICES_DIR.$hit) ) {
					$safe_s = $hit;
					$SERVICE = $SERVICES_DIR.$safe_s;
					if( $PAGESAVE )
						$page = $SERVICES_DIR.$safe_s.'/save.php';
					else
						$page = $SERVICES_DIR.$safe_s.'/page.php';
				}
			}
		}
	}
	unset($_GET["s"]);


    // Check, $_GET["r"], refererande sida (för info)
	if( isset($_GET["r"]) ) {
		$hit = array_search($_GET['r'], $dirarr);
		if ( $hit !== false ) {
			$hit = $dirarr[$hit];
			if ( $hit != '.' && $hit != '..' ) {
				if ( is_dir($SERVICES_DIR.$hit) ) {
					$safe_r = $hit;
				}
			}
		}
	}
	unset($_GET["r"]);

    // inkludera $page om det inte är en save.php och formuläret ej ändrats
	if( !( (isset($_POST['b_ok']) || isset($_POST['b_apply']) ) && $_POST['form_status'] != 'changed' ) )
		require($page);

    // Har fel skett och save.php körts..
	if( $ERROR != "" AND $PAGESAVE ) {
		$getstr = 's='.$safe_s.'&e='.$ERROR;
		if( isset($_GET['t']) )
			 $getstr .= '&t='.$_GET['t'];
		if( isset($INFO) )
			$getstr .= '&i='.$INFO;
		foreach( $GET AS $name => $value )
			$getstr .= '&'.$name.'='.$value;
		header('Location: main.php?'.$getstr);
		exit();
	}

    // Har knapp tryckts?
	if( isset($_POST['b_ok']) ) {
		$getstr = 'r='.$safe_s;
		if( isset($_POST['parent_page'])  ) {
			if( isset($_POST['parent_tab']) )
				$getstr .= '&s='.$_POST['parent_page'].'&t='.$_POST['parent_tab'];
			else
				$getstr .= '&s='.$_POST['parent_page'];
		}
		if( isset($INFO) )
			$getstr .= '&i='.$INFO;
		header('Location: main.php?'.$getstr);
		exit();
	}
	else if( $PAGESAVE ) {
		$getstr = 's='.$safe_s;
		if( isset($_GET['t']) )
			 $getstr .= '&t='.$_GET['t'];
		if( isset($INFO) ) {
			$getstr .= '&i='.$INFO;
		}
		foreach( $GET AS $name => $value )
			$getstr .= '&'.$name.'='.$value;
		header('Location: main.php?'.$getstr);
		exit();
	}




////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////


    function html_start(array $tabs=NULL, $refresh=NULL, $javascript=NULL)
    {
	global $BASE_DIR;
	global $SERVICES_DIR;
	global $ERROR;
	global $INFO;
	global $safe_s;
	global $safe_r;

	// Tolka felkod som kommer från denna eller tidigare php-sida
	if( isset($_SESSION['error']) ) {
		$arr = @parse_ini_file( $SERVICES_DIR.$safe_s."/template", 1 );
		if( $arr !== FALSE )
			$ERROR = $arr['error'][ $_SESSION['error'] ];
		unset( $_SESSION['error'] );
	}
	

	// Tolka infokod som kommer från denna eller tidigare php-sida
	if( isset($_SESSION['info']) ) {
		if( isset($safe_r) )
			$map = $safe_r;
		else
			$map = $safe_s;
		$arr = @parse_ini_file( $SERVICES_DIR.$map."/template", 1 );
		if( $arr !== FALSE )
			$INFO = $arr['info'][ $_SESSION['info'] ];
		unset( $_SESSION['info'] );
	}
	
	
	echo "\n";
?>
	<html>
	<head>
	<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<?php 
	if( $refresh!== NULL )
		echo '<meta http-equiv="refresh" content="'.$refresh.'">';
	else
		echo '<meta http-equiv="refresh" content="610">';  //auto logout
?>
	<title><? title();?></title>
	<link rel="stylesheet" type="text/css" href="css.css" />

	
	<script defer type="text/javascript" src="pngfix.js"></script>

	<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
	<!-- Hide script from old browsers

	// Skapar prototyp indexOf för läsare som inte ännu implementerat detta
	if (!Array.prototype.indexOf) {
		Array.prototype.indexOf = function(val, fromIndex) {
			if (typeof(fromIndex) != 'number') fromIndex = 0;
			for (var index = fromIndex,len = this.length; index < len; index++)
				if (this[index] == val) return index;
			return -1;
		}
	}

	var state = 'none';
	function showhide(layer_ref) {
		if (state == 'block') {
		state = 'none';
		} else {
			state = 'block';
		}
		if (document.all) { //IS IE 4 or 5 (or 6 beta)
			eval( "document.all." + layer_ref + ".style.display = state");
		}
		if (document.layers) { //IS NETSCAPE 4 or below
			document.layers[layer_ref].display = state;
		}
		if (document.getElementById &&!document.all) {
			hza = document.getElementById(layer_ref);
			hza.style.display = state;
		}
	}

	//Växlar synlighet på angivet element
	function switchhidden( id )
	{
		if( document.getElementById(id).style.display == '' )
			document.getElementById(id).style.display = 'none';
		else
			document.getElementById(id).style.display = '';
	}

	/*
	AJAX-javascriptfunktioner
	*/
	function ajax_start() {
		/* Create a new XMLHttpRequest object to talk to the Web server */
		var xmlHttp = false;
		/*@cc_on @*/
		/*@if (@_jscript_version >= 5)
		try {
		  xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
		  try {
		    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		  } catch (e2) {
		    xmlHttp = false;
		  }
		}
		@end @*/

		if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
		  xmlHttp = new XMLHttpRequest();
        	}
        	return xmlHttp;
	}

	function ajax_send( page, rtype, rvalue, msg, func_data ) {
	/*
	Sänder 'msg' till 'page'
	rtype kan vara 'htmlid' eller 'jsfunc'
	rtype = htmlid: rvalue innehåller id på htmlobjektet som ska få ombytt htmlkod
	rtype = jsfunc: rvalue innehåller länk till javascriptfunktion som ska anropas när svar kommer
	*/
	  var url = encodeURI("getf.php?s=" + <? echo "\"$safe_s\"" ?> + "&f=" + page + "&msg=" + msg);

	  var xmlHttp = ajax_start();
	  xmlHttp.open("GET", url, true);
	  xmlHttp.setRequestHeader('Content-type','text/html; charset=utf-8');

	  switch( rtype ) {
	  case 'jsfunc':
	    xmlHttp.onreadystatechange = function() { ajax_checkresponse( xmlHttp, rvalue, func_data ); }
	    break;
	  case 'htmlid':
	    xmlHttp.onreadystatechange = function() { ajax_htmlid( xmlHttp, rvalue ); }
	    break;
	  }

	  xmlHttp.send(false);

	}

	function ajax_htmlid( xmlHttp, rvalue ) {
	      if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
		if( rvalue != "" )
			document.getElementById( rvalue ).innerHTML = xmlHttp.responseText;
	      }
	}


	function ajax_checkresponse( xmlHttp, rvalue, func_data ) {
	  if (xmlHttp.readyState == 4) {
	    if (xmlHttp.status == 200) {
	      if( func_data === false )
	      	rvalue( xmlHttp );
	      else
	      	rvalue( xmlHttp, func_data );
	    }
	    //else {
	    //	alert("Fel i kommunikation med server. Kod: " + xmlHttp.status);
	    //}
	  }
	}

	/*
	Visa och dölj hjälpruta
	*/
	document.write("<div id='helpbox' style='z-index: 255' onClick='helpbox_animate()'>no text</div>");

	helpbox_time_id = 0;
	helpbox_time_start = 0;
	function helpbox_start( txt ) {
		clearTimeout( helpbox_time_id );
		clearTimeout( helpbox_time_start );
		helpbox_time_start = setTimeout("helpbox_create('"+txt+"')", 200);
	}

	function helpbox_create( txt ) {
		clearTimeout( helpbox_time_id );
		helpbox_opacity = 95;
		document.getElementById("helpbox").style.visibility ="visible";
		document.getElementById("helpbox").innerHTML= txt;
		document.getElementById("helpbox").style.filter = "alpha(opacity="+helpbox_opacity+")";
		document.getElementById("helpbox").style.opacity = helpbox_opacity/100;
	}

	function helpbox_hold() {
		clearTimeout( helpbox_time_id );
		clearTimeout( helpbox_time_start );
		helpbox_opacity = 95;
		document.getElementById("helpbox").style.filter = "alpha(opacity="+helpbox_opacity+")";
		document.getElementById("helpbox").style.opacity = helpbox_opacity/100;
	}
	
	function helpbox_stop() {
		clearTimeout( helpbox_time_start );
		helpbox_time_id = setTimeout("helpbox_animate()", 200);
	}

	function helpbox_animate() {
		if( helpbox_opacity >= 8 ) {
			helpbox_opacity -= 8;
			document.getElementById("helpbox").style.filter = "alpha(opacity="+helpbox_opacity+")";
			document.getElementById("helpbox").style.opacity = helpbox_opacity/100;
			helpbox_time_id = setTimeout("helpbox_animate()", 50);
		} 
		else {
			document.getElementById("helpbox").style.visibility ="hidden";
		}
	}

	
	/*
	Kontrollerar om formuläret har blivit uppdaterat
	*/
	function checkF_status(oForm) {
		var el, opt, i = 0, j;
		while (el = oForm.elements[i++]) {
			switch (el.type) {
			case 'text' :
			case 'textarea' :
			case 'password' :
				if (el.value != el.defaultValue)
					F_isChanged(oForm);
				break;
			case 'radio' :
			case 'checkbox' :
				if ((el.checked && !el.defaultChecked) || (!el.checked && el.defaultChecked))
					F_isChanged(oForm);
				break;
			case 'select-one' :
			case 'select-multiple' :
				j = 0;
				while (opt = el.options[j++])
					if ((opt.selected && !opt.defaultSelected) || (!opt.selected && opt.defaultSelected))
						F_isChanged(oForm);
				break;
			}
		}
	}

	function F_isChanged(oForm) {
		document.pageform.form_status.value = 'changed';
	}
		


	/*
	Visa informationsbox som kommer upp ala msn
	*/
<?php
	if( $INFO != "" ) {
?>
		info_height = 0;
		info_counter = 0;
		document.write("<div id='info_tab'><? echo $INFO ?></div>");
		function info_animate() {
			document.getElementById("info_tab").style.visibility ="visible";
			if( info_counter <= 20) {
				info_height += 0.3;
			}
			if( info_counter >= 100 ) {
				info_height -= 0.3;
			}
			if( info_counter < 120 ) {
				document.getElementById("info_tab").style.height = info_height+"em";
				info_counter += 1;
				setTimeout("info_animate()", 50);
			}
			else {
				document.getElementById("info_tab").style.visibility ="hidden";
			}
		}
		setTimeout("info_animate()", 800);
<?php 
	}

	if( $javascript !== NULL )
		echo $javascript;
?>
	 
	// End hiding script from old browsers -->
	</SCRIPT>
	</head>
        <body>
<?php
	if( $ERROR != "" )
		echo '<body onLoad="document.pageform.form_status.value = \'unchanged\'; alert(\''.$ERROR.'\')">';
	else
		echo '<body onLoad="document.pageform.form_status.value = \'unchanged\';">';
?>
	<center>
<?php
	$getstr = 's='.$safe_s;
	foreach( $_GET AS $name => $value )
		$getstr .= '&'.$name.'='.$value;
	echo '<form name="pageform" action="main.php?'.$getstr.'" method=POST onSubmit="checkF_status(this)">';
	echo '<input type="hidden" name="form_status" value="changed">';
?>
	<table width="799" cellspacing="0" cellpadding="0">
	<tr><td class="head" valign="top">
	<? require($BASE_DIR."inc/header.php") ?></td></tr>
<?php 
	//$tabs[]=array('name','name');$tabs[]=array('name','name');$tabs[]=array('name','name');

	if( isset($tabs) ) {
		echo '<tr><td class="" valign="bottom"">';
		for($i=0;$i<count($tabs);$i++) {
			if (!isset($_GET['t']) && $i == 0)
				$state="active";
			elseif (isset($_GET['t']) && $tabs[$i][0] == $_GET['t'])
				$state="active";
			else
				$state="passive";
			echo '
				<table cellspacing="0" cellpadding="0" style="float:left; ">
				<tr>
				<td style="background-image:url(\'images/tab-'.$state.'-left.png\'); width:12px; height:22px; "></td>
				<td style="background-image:url(\'images/tab-'.$state.'-middle.png\'); height:22px; ">
					<a href="main.php?s='.$safe_s.'&amp;t='.$tabs[$i][0].'">'.$tabs[$i][1].'</a>
				</td>
				<td style="background-image:url(\'images/tab-'.$state.'-right.png\'); width:12px; height:22px; "></td></tr>
				</table>
			';
		}
		echo '
			<table cellspacing="0" cellpadding="0" style="float:left; ">
			<tr>
			<td style="background-image:url(\'images/tab-bottom.png\'); width:800px; height:22px; "></td>
			</tr>
			</table>
		';
		echo '</td></tr>';
		echo '<tr><td class="body" style="height:20px; "></td></tr>';
	} else {
		echo '
			<tr><td class="" valign="bottom"">
			<table cellspacing="0" cellpadding="0" style="float:left; ">
			<tr>
			<td style="background-image:url(\'images/bodyhead.png\'); width:800px; height:20px; "></td>
			</tr>
			</table>
			</td></tr>
		';
	}
?>
	<tr><td class="body" valign="top">

<?php
}


function html_end($bOk=FALSE, $bApply=FALSE, $bCancel=FALSE, $parent_page=FALSE, $parent_tab=FALSE)
{
	global $BASE_DIR;
	global $ERROR;
	global $safe_s;
?>
	</td></tr>
	<tr><td class="body" style="text-align: center">
<?php
	if( $parent_page ) {
		echo '<input type="hidden" name="parent_page" value="'.$parent_page.'">';
	}
	if( $parent_tab ) {
		echo '<input type="hidden" name="parent_tab" value="'.$parent_tab.'">';
	}
	if( $safe_s == "" ) {
		echo '<input type=submit class="button" name="b_logout" value="Logga ut">';
		echo '<a href="?s=log" style="float: right; height: 0em; font-size: 70%; color: #00f">visa log</a>';
	}
	else if( $bOk==FALSE AND $bApply==FALSE AND $bCancel==FALSE) {
		echo '<input type=submit class="button" name="b_close" value="Stäng">';
	}
	else {
		if( $bOk )
			echo '<input type=submit class="button" name="b_ok" value="Ok">';
		if( $bApply )
			echo '<input type="submit" class="button" name="b_apply" value="Verkställ">';
		if( $bCancel )
			echo '<input type=submit class="button" name="b_cancel" value="Avbryt">';
	}
?>
	</td></tr>
	<tr><td class="foot"><? require($BASE_DIR."inc/footer.php") ?></td></tr>

	</table>
	</form>
	</center>
	</body>
	</html>
<?php
}
?>
